$(function(){
	// 页面加载完成建立分页
	showPage(current,pages);

	// 实现方法
	list = function(page){
		var ll = layer.load();
		
		if(!page){
			page = 1;
		}
		
		searchForm.pageNum.value = page;
		
		$.post(basePath + "/repairRecord/list",$("#searchForm").serialize(),function(data){
			$("#contentTBody").html(data);
			showPage(current,pages);
			layer.close(ll);
		},'html');
	};
	
	preview = function(seqId){
		var ll = layer.load();
		$.post(basePath + "/repairRecord/preview",{seqId: seqId},function(data){
			layer.open({
				  type: 1,
				  title: '详情',
				  closeBtn: 1,
				  area: [$("#contentDiv").width() + 'px', '500px'],
				  shadeClose: true,
				  content: data,
				  btn: ['确认','导出计算过程'],
				  yes: function(index){
					  layer.close(index);
				  },
				  btn2: function(index){
					  var url = basePath+'/repairRecord/exportCalculate?seqId='+seqId;

					  var form = document.createElement("form");
					  form.action = url;
					  form.method = "post";

					  $(document.body).append(form);

					  form.submit();
					  $(form).remove();
					  return false;
				  }
				});
			layer.close(ll);
		},'html');
	};
	
	add = function(){
		var ll = layer.load();
		$.post(basePath + "/repairRecord/detail",{},function(data){
			layer.open({
			  type: 1,
			  title: '新增',
			  closeBtn: 1,
			  area: [$("#contentDiv").width() + 'px', '500px'],
			  shadeClose: true,
			  content: data,
			  success: function(layero, index){
			    $(layero).find(".check-group input,.check-group textarea,.check-group select").each(function(index,element){
			    	var handleMsg = $(element).closest(".check-group").find(".control-label").eq(0).text();
			    	var errorMsgElement = $(element).closest(".check-group").find(".help-inline").eq(0);
			    	
	    			for(var f in checkFuntion){
	    				if($(element).hasClass(f)){
					    	for(var e in bindEvent){
					    		try{
						    		$(element).bind(bindEvent[e],{f:checkFuntion[f],element:element,msg:handleMsg,errorMsgElement:errorMsgElement},function(event){
						    			event.data.f(event.data.element,event.data.msg,event.data.errorMsgElement);
						    		});
					    		} catch(e){
					    			
					    		}
					    	}
	    				}
	    			}
			    });
			    
			    nameMap = emptyNameMap;
			    // 先将初始值加载
			    $(layero).find("#lossVoltageLevelParam input[name^='params[']").each(function(){
			    	var name = this.name.replace('params[','').replace(']',''); 
			    	nameMap[name] = this.value;
		    	});
			    $(layero).find("#lossVoltageLevelParam input[name^='params[']").bind('change',function(){
			    	if($(this).closest("check-group").find("check-error").length == 0){
				    	var name = this.name.replace('params[','').replace(']',''); 
				    	nameMap[name] = this.value;
				    	
				    	// 检查是否所有所需参数都已经设定完毕
				    	var allReady = true;
				    	for(var i in nameMap){
				    		if(!nameMap[i]){
				    			allReady = false;
				    			break;
				    		}
				    	}
				    	
				    	if(allReady){
				    		var resultArray = calculate();
				    		
				    		$("#calculateResult input:disabled").each(function(index){
				    			this.value = resultArray[index];
				    		});
				    	}
			    	}
			    });
			  },
			  btn: ['确认', '取消'],
			  yes: function(index, layero){
				  var sl = layer.load();
				  save(null,sl,index);
			  }
			});
			
			layer.close(ll);
		},'html');
	};
	
	modify = function(seqId){
		var ll = layer.load();
		$.post(basePath + "/repairRecord/detail",{seqId: seqId},function(data){
			layer.open({
			  type: 1,
			  title: '修改',
			  closeBtn: 1,
			  area: [$("#contentDiv").width() + 'px', '500px'],
			  shadeClose: true,
			  content: data,
			  success: function(layero, index){
			    $(layero).find(".check-group input,.check-group textarea,.check-group select").each(function(index,element){
			    	var handleMsg = $(element).closest(".check-group").find(".control-label").eq(0).text();
			    	var errorMsgElement = $(element).closest(".check-group").find(".help-inline").eq(0);
			    	
	    			for(var f in checkFuntion){
	    				if($(element).hasClass(f)){
					    	for(var e in bindEvent){
					    		try{
						    		$(element).bind(bindEvent[e],{f:checkFuntion[f],element:element,msg:handleMsg,errorMsgElement:errorMsgElement},function(event){
						    			event.data.f(event.data.element,event.data.msg,event.data.errorMsgElement);
						    		});
					    		} catch(e){
					    			
					    		}
					    	}
	    				}
	    			}
			    });
			    
			    nameMap = emptyNameMap;
			    // 先将初始值加载
			    $(layero).find("#lossVoltageLevelParam input[name^='params[']").each(function(){
			    	var name = this.name.replace('params[','').replace(']',''); 
			    	nameMap[name] = this.value;
		    	});
			    $(layero).find("#lossVoltageLevelParam input[name^='params[']").bind('change',function(){
			    	if($(this).closest("check-group").find("check-error").length == 0){
				    	var name = this.name.replace('params[','').replace(']',''); 
				    	nameMap[name] = this.value;
				    	
				    	// 检查是否所有所需参数都已经设定完毕
				    	var allReady = true;
				    	for(var i in nameMap){
				    		if(!nameMap[i]){
				    			allReady = false;
				    			break;
				    		}
				    	}
				    	
				    	if(allReady){
				    		var resultArray = calculate();
				    		
				    		$("#calculateResult input:disabled").each(function(index){
				    			this.value = resultArray[index];
				    		});
				    	}
			    	}
			    });
			  },
			  end: function(){
				$(".datetimepicker").remove();  
			  },
			  btn: ['确认', '取消'],
			  yes: function(index, layero){
				  var sl = layer.load();
				  save(seqId,sl,index);
			  }
			});
			
			layer.close(ll);
		},'html');
	};
	
	save = function(seqId,sl,lidx){
		$("#dataForm").find(".check-group input,.check-group select,.check-group textarea").blur();
		
		if($("#dataForm").find(".check-error").length > 0){
			layer.close(sl);
			return false;
		}
		
		var actionPath;
		
		if(!!seqId){
			actionPath = basePath + "/repairRecord/update";
		}
		else{
			actionPath = basePath + "/repairRecord/insert";
		}
		

		var obj = $("#dataForm").serializeObject();
		var params = {};
		
		for(var i in obj){
			if(/params[\S*]/.test(i)){
				params[i.replace('params[','').replace(']','')] = obj[i];
				delete obj[i];
			}
		}
		obj.params = JSON.stringify(params);
		if(obj.imgSeqIds){
			if(!Array.isArray(obj.imgSeqIds)){
				obj.imgSeqIdstr = obj.imgSeqIds;
			}
			else{
				obj.imgSeqIdstr = obj.imgSeqIds.join("@#@");
			}
		}
		else{
			obj.imgSeqIdstr = "";
		}
		
		$.post(actionPath,obj,function(data){
			layer.close(sl);
			var result = dealData(data);
			if(result){
				layer.close(lidx);
				list();
			}
		},'html');
	};
	
	del = function(seqId){
		var ll = layer.load();
		
		var l1 = layer.open({
			  type: 1,
			  title: '删除该故障记录',
			  closeBtn: 1,
			  area: ['300px', '140px'],
			  shadeClose: true,
			  content: '<div class="alert alert-error" style="margin: 0">请确认是否<strong>删除该故障记录</strong></div>',
			  btn: ['确认删除', '取消'],
			  success: function(layero, index){
				  layer.close(ll);
			  },
			  yes: function(index, layero){
				  $.post(basePath + "/repairRecord/delete",{seqId : seqId},function(data){
					switch(data){
						case 'DB_ER' :
							layer.msg('删除时遇到错误', {
								time: 2000, //2s后自动关闭
								btn: ['关闭'],
								icon: 2,
								title: '消息提示'
							});
							break;
						case 'success' :
							layer.msg('删除成功', {
								time: 1000, //1s后自动关闭
								icon: 1,
								title: '消息提示'
							});
							list();
							break;
					};
					layer.close(l1);
				  },'html');
			  }
			});
	};
	
	chooseCustomer = function(seqId){
		var ll = layer.load();
		
		$.post(basePath + "/repairRecord/customerList",{oldSeqId: seqId},function(data){
			moveLayerId = layer.open({
			  type: 1,
			  title: '选择户号',
			  closeBtn: 1,
			  area: [$("#contentDiv").width() + 'px', '600px'],
			  shadeClose: true,
			  content: data
			});
			
			layer.close(ll);
		},'html');
	};
	
	customerList = function(pageNum,seqId){
		var ll = layer.load();
		moveSearchForm.pageNum.value = pageNum;
		
		$.post(basePath + "/repairRecord/customerList",$("#moveSearchForm").serialize(),function(data){
			$("#moveSearchForm").parent().html(data);
			layer.close(ll);
		},'html');
	};
	
	selectCustomer = function(seqId,customerNumber,customerName){
		$("#customerNumberData").val("[" + customerNumber + "]" + customerName);
		$("#customerNumberData").nextAll("[name='customerNumber']").val(seqId);
		$("#customerNumberData").change();
		$("#customerNumberData").nextAll("[name='customerNumber']").change();
		layer.close(moveLayerId);
	};
	
	var dealData = function(data){
		data = eval("(" + data + ")");
		
		if(data.flag == 'success'){
			layer.msg(data.msg, {
				time: 1000, //1s后自动关闭
				icon: 1,
				title: '消息提示'
			});
			return true;
		}
		else{
			layer.msg(data.msg, {
				//2s后自动关闭 time: 2000, 
				btn: ['关闭'],
				icon: 2,
				title: '消息提示'
			});
			return false;
		}
	}
	
	var calculate = function(){
		var obj = $("#dataForm").serializeObject();
		var params = {};
		
		for(var i in obj){
			if(/params[\S*]/.test(i)){
				params[i.replace('params[','').replace(']','')] = obj[i];
				delete obj[i];
			}
		}
		
		var days1 = Math.ceil((toDate(params[keyArray[4][1]]).getTime() - toDate(params[keyArray[4][0]]).getTime()) / 1000 / 60 / 60 / 24);
		var days2 = Math.ceil((toDate(params[keyArray[4][2]]).getTime() - toDate(params[keyArray[4][1]]).getTime()) / 1000 / 60 / 60 / 24);
		var days3 = Math.ceil((toDate(params[keyArray[4][3]]).getTime() - toDate(params[keyArray[4][2]]).getTime()) / 1000 / 60 / 60 / 24);
		
		var resultArray = new Array();
		
		for(var i = 0;i < keyArray[0].length;i++){
			var temp1 = parseFloat(params[keyArray[1][i]]) - parseFloat(params[keyArray[0][i]]);
			var temp2 = parseFloat(params[keyArray[2][i]]) - parseFloat(params[keyArray[1][i]]);
			var temp3 = parseFloat(params[keyArray[3][i]]) - parseFloat(params[keyArray[2][i]]);
			
			var avg1 = days1 == 0 ? 0 : temp1 * parseFloat(params[keyArray[5][0]]) * parseFloat(params[keyArray[5][1]]) / days1;
			avg1 = Math.round(avg1 * 100) / 100;
			var avg3 = days3 == 0 ? 0 : temp3 * parseFloat(params[keyArray[5][0]]) * parseFloat(params[keyArray[5][1]]) / days3;
			avg3 = Math.round(avg3 * 100) / 100;
			var avg2 = (avg1 + avg3) / 2;
			avg2 = Math.round(avg2 * 100) / 100;
			
			var lossResult = avg2 * days2;
			lossResult = Math.round(lossResult * 100) / 100;
			
			var tempResult = temp2 * parseFloat(params[keyArray[5][0]]) * parseFloat(params[keyArray[5][1]]);
			tempResult = Math.round(tempResult * 100) / 100;
			
			var result = lossResult - tempResult;
			result = Math.round(result * 100) / 100;
			
			resultArray.push(result);
		}
		
		resultArray.push(resultArray[0]);
		for(var i = 1;i < resultArray.length - 1;i++){
			resultArray[resultArray.length - 1] -= resultArray[i];
		}
		
		return resultArray;
	};
});